#!/bin/bash

# 输出开始信息
echo "=== Release Stage: Start ==="

# 输出所有环境变量
echo "当前环境变量："
printenv

# 检查并输出特定变量
echo "CI_API_V4_URL: ${CI_API_V4_URL}"
echo "CI_PROJECT_ID: ${CI_PROJECT_ID}"
echo "CI_COMMIT_TAG: ${CI_COMMIT_TAG}"
echo "project_api_token: ${project_api_token}"


# 设置变量
API_URL="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/releases"
TAG_NAME="${CI_COMMIT_TAG}"
RELEASE_NAME="${CI_COMMIT_TAG}"
DESCRIPTION="Release for ${CI_COMMIT_TAG}"
ASSET_NAME="output.zip"
ASSET_PATH="path/to/your/${ASSET_NAME}"

# 检查必要的环境变量是否已设置
if [[ -z "${CI_API_V4_URL}" || -z "${CI_PROJECT_ID}" || -z "${CI_COMMIT_TAG}" || -z "${project_api_token}" ]]; then
  echo "Error: 必要的环境变量未设置。"
  exit 1
fi

# 创建 Release
echo "创建 GitLab Release..."
RESPONSE=$(curl --silent --request POST --header "PRIVATE-TOKEN: ${project_api_token}" \
  --header "Content-Type: application/json" \
  --data "{\"name\": \"${RELEASE_NAME}\", \"tag_name\": \"${TAG_NAME}\", \"description\": \"${DESCRIPTION}\"}" \
  "${API_URL}")

# 检查创建 Release 的响应
if echo "$RESPONSE" | grep -q '"message"'; then
  echo "Error: 创建 Release 失败。响应: $RESPONSE"
  exit 1
else
  echo "Release 创建成功。"
fi

# 上传 Release 产物
if [[ -f "${ASSET_PATH}" ]]; then
  echo "上传 Release 产物..."
  UPLOAD_RESPONSE=$(curl --silent --request POST --header "PRIVATE-TOKEN: ${project_api_token}" \
    --form "file=@${ASSET_PATH}" \
    "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/uploads")

  # 提取文件 URL
  FILE_URL=$(echo "$UPLOAD_RESPONSE" | jq -r .url)

  if [[ -z "$FILE_URL" || "$FILE_URL" == "null" ]]; then
    echo "Error: 上传产物失败。响应: $UPLOAD_RESPONSE"
    exit 1
  else
    echo "产物上传成功，文件 URL: $FILE_URL"

    # 更新 Release 的 Assets
    echo "更新 Release 的 Assets..."
    UPDATE_RESPONSE=$(curl --silent --request PUT --header "PRIVATE-TOKEN: ${project_api_token}" \
      --header "Content-Type: application/json" \
      --data "{\"name\": \"${RELEASE_NAME}\", \"tag_name\": \"${TAG_NAME}\", \"assets\": {\"links\": [{\"name\": \"${ASSET_NAME}\", \"url\": \"${CI_PROJECT_URL}${FILE_URL}\"}]}}" \
      "${API_URL}")

    if echo "$UPDATE_RESPONSE" | grep -q '"message"'; then
      echo "Error: 更新 Release 的 Assets 失败。响应: $UPDATE_RESPONSE"
      exit 1
    else
      echo "Release 的 Assets 更新成功。"
    fi
  fi
else
  echo "Warning: 产物文件 ${ASSET_PATH} 不存在，跳过上传步骤。"
fi

echo "=== Release Stage: End ==="
